package comc.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 徐本锡
 * @Date 2019/7/4
 * @Param
 * @return
 **/
public class JWTUtil {

    private static final long EXPIRE_TIME = 5 * 60 * 1000;

    public static final String TOKEN_HEADER = "token";
    public static final String TOKEN_PREFIX = "xbx_";

    /**
     * @Author 徐本锡
     * @Description 生成token
     * @Date 2019/7/4
     * @Param
     * @return
     **/
    public static  String  createToken (String logon_name) throws UnsupportedEncodingException {

        //签名发布时间
        Date createTime = new Date();

        //设置签名过期时间  5分钟
        Calendar nowTime=Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,5);
        Date expiresTime = nowTime.getTime();
        //Date expiresTime = new Date(System.currentTimeMillis() + EXPIRE_TIME);

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("alg","HS256");//设置算法 为HS256
        map.put("typ","JWT");//设置类型为JWT

        String token= JWT.create()
                .withHeader(map)
                .withClaim("logon_name",logon_name) //可以将基本不重要的对象信息放到claims中
//                .withClaim("","")
                .withIssuedAt(createTime)//设置签发时间
                .withExpiresAt(expiresTime)//设置过去时间 过期时间大于签发时间
                .sign(Algorithm.HMAC256("123456"));//用公共密钥加密

        return token;

    }

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String logon_name, String secret) {
        try {
            //根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256("123456");
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("logon_name", logon_name)
                    .build();
            //效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getLogonName(String token) {
        try {

            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("logon_name").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
//    token的过期时间
    public static Date getTokenTime(String token) {
        return JWT.decode(token).getExpiresAt();
    }
}